package com.dashan.servlets;

import static com.dashan.Constants.USERNAME;

import java.io.IOException;
import java.util.TreeMap;

import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.dashan.backend.datastore.DsFriend;
import com.dashan.backend.datastore.DsUser;
import com.dashan.backend.datastore.UserDao;
import com.dashan.backend.util.XmlHelper;

@SuppressWarnings("serial")
public class GetFriendListServlet extends DashanPrivateServlet {

    @Override
    public String getUrlPattern() {
        return "/getfriendlist";
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        UserDao dao = new UserDao();
        try {
            DsUser user = dao.getUser(params.get(USERNAME).stringValue());
            Document xmlDoc = XmlHelper.createXmlDocument("response");
            
            Element root = xmlDoc.createElement("friendList");
            
            for (DsFriend friend : user.getFriends()) {
                root.appendChild(friend.getXmlElement(xmlDoc));
            }
            
            xmlDoc.getDocumentElement().appendChild(root);
            resp.getWriter().print(XmlHelper.xml2String(xmlDoc));
        } catch (JDOObjectNotFoundException e) {
            throw new ServletException("User not found: " + e.getMessage());
        } finally {
            dao.commit();
        }
    }

}
